<template>
   <div class="app-container">
       <el-card class="box-card" v-if="detailVisible === false">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <!-- <el-button type="danger" @click="handleDeleteAll">批量删除</el-button> -->
        </el-row>
      </div>
      <div class="item" v-loading="listLoading">
          <el-table ref="dataList" :data="menuList" style="width:100%;margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
              <!-- <el-table-column type="selection"></el-table-column> -->
              <el-table-column prop="id" label="商品组ID"> </el-table-column>
              <el-table-column prop="name" label="商品组名称"> </el-table-column>
              <el-table-column prop="status" label="状态">
                  <template slot-scope="scoped">
                      <el-tag type="success" v-if="scoped.row.status === 1">上架</el-tag>
                      <el-tag type="danger" v-if="scoped.row.status === 2">下架</el-tag>
                  </template>
              </el-table-column>
              <el-table-column prop="sort" label="优先级" > </el-table-column>
              <el-table-column prop="add_time" label="创建时间" > </el-table-column>

              <el-table-column label="操作" width="370px">
                  <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)" plain>编辑</el-button>
                  <el-button type="primary" size="mini"  @click="handleDetail(scope.row)" plain>查看详情</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row)" plain>删除</el-button>
                  <el-button type="warning" size="mini" @click="handleDown(scope.row)" plain>切换上下架</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <!-- 分页 -->
          <cus-pagination
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.perPage"
              @pagination="getList"
          />
      </div>
  </el-card>
  <!-- 删除弹框 -->
    <el-dialog
        title="确定删除吗?"
        :visible.sync="deleteDialogVisible"
        width="435px"
        >
        <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog  v-dialogDrag :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose('editRulesForm')">
        <el-form :model="editRulesForm" :rules="editRulesFormRules" ref="editRulesForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="商品组" prop="name">
                <el-input v-model="editRulesForm.name" clearable placeholder="请输入商品组"></el-input>
            </el-form-item>
            <el-form-item label="优先级" prop="sort">
                <el-input  v-model.number="editRulesForm.sort" clearable placeholder="请输入优先级"></el-input>
            </el-form-item>
            <el-form-item
                v-for="(item, index) in propBagArr"
                label="道具包"
                :key="'道具包'+index"
            >
                <el-select filterable v-model="item.reward_id" placeholder="请选择道具包" style="margin-bottom:20px">
                    <el-option
                    v-for="item in giftType"
                    :key="item.reward_id"
                    :label="item.name"
                    :value="item.reward_id">
                    </el-option>
                </el-select>
                <el-input v-model="item.name" placeholder="请输入名称" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.cost_score" placeholder="请输入兑换所需积分" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.day_limit" placeholder="请输入每天兑换次数" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.number" placeholder="请输入数量" style="margin-bottom:20px"></el-input>
                <el-input v-model="item.remark" type="textarea" placeholder="请输入备注" style="margin-bottom:20px"></el-input>
                <el-button @click.prevent="removeGift(item)">删除</el-button>
            </el-form-item>
            <el-form-item
                v-for="(item, index) in propArr"
                label="道具"
                :key="'道具'+index"
            >
                <el-select filterable v-model="item.reward_id" placeholder="请选择道具" style="margin-bottom:20px">
                    <el-option
                    v-for="item in propType"
                    :key="item.reward_id"
                    :label="item.name"
                    :value="item.reward_id">
                    </el-option>
                </el-select>
                <el-input v-model="item.name" placeholder="请输入名称" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.cost_score" placeholder="请输入兑换所需积分" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.day_limit" placeholder="请输入每天兑换次数" style="margin-bottom:20px"></el-input>
                <el-input v-model.number="item.number" placeholder="请输入数量" style="margin-bottom:20px"></el-input>
                <el-input v-model="item.remark" type="textarea" placeholder="请输入备注" style="margin-bottom:20px"></el-input>
                <el-button @click.prevent="removeProp(item)">删除</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addGift">新增道具包</el-button>
                <el-button type="primary" @click="addProp">新增道具</el-button>
            </el-form-item>
            <el-form-item>
                <el-button @click="dialogFormVisible = false">返回</el-button>
                <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
            </el-form-item>
            </el-form>
    </el-dialog>
    <!-- 查看详情 -->
    <el-card class="box-card" v-if="detailVisible">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="primary" @click="detailVisible = false">&emsp;返回&emsp;</el-button>
        </el-row>
      </div>
      <div class="item">
        <el-table class="detailTable" ref="dataList2" :data="detailList" style="width:100%;margin-bottom: 20px;" row-key="id" border :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
            <el-table-column label="商品组ID" prop="group_id"></el-table-column>
            <!-- <el-table-column label="商品组名称" prop="name"></el-table-column> -->
            <el-table-column label="商品ID" prop="id"></el-table-column>
            <el-table-column label="商品名称" prop="name"></el-table-column>
            <el-table-column prop="reward_data" label="商品道具内容" width="230">
                <template slot-scope="scope">
                    <div v-for="(item,index) in scope.row.reward_data" :key="index" >
                        <div v-if="item.type === 5">
                            <el-tag type="warning">金币✖{{item.number}}</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                        <div v-if="item.type === 1">
                            <el-tag type="danger">积分✖{{item.number}}</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                        <div v-if="item.type === 4">
                            <el-tag type="primary">{{item.name}}✖{{item.number}}个</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                        <div v-if="item.type === 3">
                            <el-tag type="primary">{{item.name}}✖{{item.number}}天</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                        <div v-if="item.type === 2">
                            <el-tag type="primary">{{item.name}}✖{{item.number}}天</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                        <div v-if="item.type === 6">
                            <el-tag type="primary">{{item.name}}✖{{item.number}}天</el-tag><el-tag type="info" v-if="item.weight">{{item.weight}}%</el-tag>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="每日兑换次数" prop="day_limit"></el-table-column>
            <el-table-column label="兑换所需积分" prop="cost_score"></el-table-column>
            <el-table-column label="数量" prop="number"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="上架时间" prop="add_time"></el-table-column>
        </el-table>

          <!-- 分页 -->
          <cus-pagination
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.perPage"
              @pagination="getList"
          />
      </div>
  </el-card>
   </div>
</template>

<script>
import {
    listData,
    listDetailData,
    putData,
    listTypeData,
    listPropData,
    updateData,
    deleteData
} from '@/api/rewardPoint/shopmall'

export default {
    data(){
        return {

            // 详情
            detailList:[],
            detailVisible:false,

            // 要修改的当前行的id
            row_id:0,
            // 黑名单类别
            blackList:[
                {value:1,label:'1'},
                {value:2,label:'4'},
                {value:3,label:'6'},
                {value:4,label:'3'},
                {value:5,label:'5'}
            ],
            // 选中的黑名单类别
            checkBlackList:[],
            provinceList:[],
            cityList:[],
            // 表单规则
            editRulesFormRules:{
                name:[{ required: true, message: '请输入商品组名称', trigger: 'blur' }],
                sort:[{ required: true, message: '请输入排序', trigger: 'blur' }],
            },
            // 受限类型
            limit_typeList:[
                {value:1,label:'全部'},
                {value:2,label:'IP'},
                {value:3,label:'归属地'},
            ],
            giftType:[],
            propType:[],
            propBagArr:[],
            propArr:[],
            editRulesForm:{
                name:undefined,
                sort:undefined,
                id:0,
                product_details:[]
            },
            dialogStatus: '',
            // dialog的头部信息
            titleMap: {
                update: '编辑',
                create: '添加'
            },
            dialogFormVisible:false,
            deleteDialogVisible:false,
            listLoading:false,
            menuList:[{
                id:1,
                info:'test2',
                need_user_level:222,
                cate:1,
                state:'1'
            }],
            limitList:[],
            listQuery:{
                page:1,
                perPage:10,
            },
            total:0,
            // 勾选内容
            multipleSelection: [],
            // 要删除的内容的ids
            dataIds:'',
        }
    },
    created(){
        this.getList()
        this.getTypeList()
        this.getPropList()
    },
    methods:{

        getList(){
            this.listLoading = true;
            let urlData = "?";
            if (this.listQuery.page) {
                urlData = urlData + `page=${this.listQuery.page}&`;
            }
            if (this.listQuery.perPage) {
                urlData = urlData + `perPage=${this.listQuery.perPage}`;
            }
            listData(urlData).then((response) => {
                this.menuList = response.data.data;
                this.total = response.data.total;
                this.listLoading = false
            })
        },
        getTypeList(){
            listTypeData('?page=1&perPage=100000').then(response => {
                response.data.data.forEach(item => {
                    this.giftType.push({reward_id:item['id'],name:item['name']})
                })

            })
        },
        getPropList(){
            listPropData('?page=1&perPage=100000').then(response => {
                response.data.data.forEach(item => {
                    this.propType.push({reward_id:item['id'],name:item['name']})
                })
            })
        },
        // 点击新增
        handleCreate(){
            this.resetForm('editRulesForm')
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
        },
        // 添加商品
        addGift(){
            this.propBagArr.push({
                remark:'',
                number:'',
                reward_id:'',
                cost_score:'',
                day_limit:'',
                name:'',
                id:0,
                type:1,
            });
        },
        addProp(){
            this.propArr.push({
                remark:'',
                number:'',
                reward_id:'',
                cost_score:'',
                day_limit:'',
                name:'',
                id:0,
                type:2
            });
        },
        handleDown(row){
            let obj = {id:row.id}
            obj.type = row.status === 1 ? 2 : 1;
            updateData(obj).then(response => {
                if (response.code === 200) {
                    this.getList()
                    this.$notify({
                        type:'success',
                        message: '操作成功',
                        position: 'bottom-right',
                        showClose: false,
                        duration: 3000
                    });
                } else {
                    this.$message({
                        message: response.message,
                        type: 'error'
                    });
                }
            })
        },


        removeGift(item){
            let index = this.propBagArr.indexOf(item)
            if (index !== -1) {
                this.propBagArr.splice(index, 1)
            }
        },
        removeProp(item){
            let index = this.propArr.indexOf(item)
            if (index !== -1) {
                this.propArr.splice(index, 1)
            }
        },
        // 点击编辑
        handleUpdate(row){
            this.propBagArr = []
            this.propArr = []
            listDetailData(`?group_id=${row.id}`).then(response => {
                response.data.forEach(item => {
                    if(item.type === 1){
                        this.propBagArr.push({id:item.id,name:item.name,reward_id:item.reward_id,cost_score:item.cost_score,day_limit:item.day_limit,type:item.type,remark:item.remark,number:item.number})
                    }else if(item.type === 2){
                        this.propArr.push({id:item.id,name:item.name,reward_id:item.reward_id,cost_score:item.cost_score,day_limit:item.day_limit,type:item.type,remark:item.remark,number:item.number})
                    }
                })
            })
            this.editRulesForm.sort = row.sort;
            this.editRulesForm.name = row.name;
            this.editRulesForm.id = row.id
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
        },
        // 重置表单内容
        resetForm(formName) {
            this.$nextTick(()=>{
                // this.$refs[formName].resetFields();
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
                this.editRulesForm = {
                    name:undefined,
                    sort:undefined,
                    id:0,
                    product_details:[]
                }
                this.propArr = []
                this.propBagArr = []
            })

        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.dialogStatus === 'create'){
                        this.editRulesForm.product_details = [...this.propBagArr,...this.propArr]
                        putData(this.editRulesForm).then(response => {
                            if (response.code === 200) {
                                this.getList()
                                this.dialogFormVisible = false;
                                this.$notify({
                                    type:'success',
                                    message: '操作成功',
                                    position: 'bottom-right',
                                    showClose: false,
                                    duration: 3000
                                });
                            } else {
                                this.$message({
                                    message: response.message,
                                    type: 'error'
                                });
                            }
                        })
                    }else {
                        this.editRulesForm.product_details = [...this.propBagArr,...this.propArr]
                        putData(this.editRulesForm).then(response => {
                            if (response.code === 200) {
                                this.getList()
                                this.dialogFormVisible = false;
                                this.$notify({
                                    type:'success',
                                    message: '操作成功',
                                    position: 'bottom-right',
                                    showClose: false,
                                    duration: 3000
                                });
                            } else {
                                this.$message({
                                    message: response.message,
                                    type: 'error'
                                });
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        // 点击查看详情
        handleDetail(row){
            this.row_id = row.id;
            listDetailData(`?group_id=${this.row_id}`).then(response => {
                this.detailList = response.data
                this.detailVisible = true
            })
        },
        // 勾选
        handleSelectionChange(val) {
        this.multipleSelection = val;
        },
        // 点击单个删除
        handleDelete(row) {
            this.dataIds = {ids:[row.id]}
            this.deleteDialogVisible = true
        },
        // 点击批量删除
        handleDeleteAll(){
            if(this.multipleSelection.length === 0){
                this.$message({
                    message: '请先勾选要删除的内容',
                    type: 'warning'
                });
                return;
            }else if(this.multipleSelection.length !== 0){
                let ids = '';
                for(let key in this.multipleSelection){
                    ids+=`${this.multipleSelection[key].id},`
                }
                ids = ids.substring(0, ids.length - 1)
                this.dataIds = {ids:ids}
            }
            this.deleteDialogVisible = true
        },
        // 确定删除
        confirmDelete(){

            // this.dataIds)
            deleteData(this.dataIds).then((response) => {
                if (response.code === 200) {
                    this.getList()
                    this.deleteDialogVisible = false;
                    this.$notify({
                        type:'success',
                        message: '操作成功',
                        position: 'bottom-right',
                        showClose: false,
                        duration: 3000
                    });
                } else {
                    this.$message({
                        message: response.message,
                        type: 'error'
                    });
                }
            })
        },
        // 监听dialog关闭时的处理事件
        handleDialogClose(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].clearValidate(); // 清除整个表单的校验
            }
        },
    }
}
</script>

<style scoped>
[v-cloak] {
        display: none;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    .box-card {
        width: 100%;
    }

    .demo-form-inline {
        float: right;
    }

    .el-table .tagDiv {
        display: block;
    }

    .detailTable /deep/.el-table_1_column_4 .cell {
        display: flex;
        flex-direction:column ;
    }
    .detailTable /deep/.el-table_1_column_4 .cell>div {
        margin-bottom: 10px;
    }

    /deep/.el-upload-list__item {
        transition: none !important;
    }

   /*  /deep/ .el-card__header {
        padding-bottom: 0;
    }
 */

</style>
